import java.sql.Time;
import java.util.PriorityQueue;
import java.util.TimerTask;

public class CreatTimer {
    public static class MyTimerTask implements Comparable<MyTimerTask>{
private Runnable task;
private long time;
        public MyTimerTask(Runnable task, long time) {
            this.task = task;
            this.time = time;
        }

        public Runnable getTask() {
            return task;
        }

        public long getTime() {
            return time;
        }

        @Override
        public int compareTo(MyTimerTask o) {
            return (int) (this.getTime()-o.getTime());
        }
    }
    static class MyTimer{
        private PriorityQueue<MyTimerTask>queue=new PriorityQueue<>();
Object lock=new Object();
        public void schedule(Runnable task,long time){
            synchronized (lock){
                MyTimerTask task1=new MyTimerTask(task,time+System.currentTimeMillis());
                queue.offer(task1);
                lock.notify();
}
        }
        public MyTimer() {
            Thread thread=new Thread(()->{
while (true){
     try {
         synchronized (lock){
             while (queue.isEmpty()){
                 lock.wait();
             }
             MyTimerTask task= queue.peek();
             if(task.getTime()>System.currentTimeMillis()){
                 lock.wait(task.getTime()-System.currentTimeMillis());
             }else {
                 task.getTask().run();
                 queue.poll();
             }
         }
     } catch (InterruptedException e) {
         throw new RuntimeException(e);
     }
}
            });
            thread.start();
        }
    }

    public static void main(String[] args) {
        MyTimer timer=new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("我是任务1");
            }
        },1000);
timer.schedule(new Runnable() {
    @Override
    public void run() {
        System.out.println("我是任务2");
    }
},2000);

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("我是任务3");
            }
        },3000);

    }
}
